import React, { useState, useEffect } from 'react';
import { Input, Row, Col, Tooltip } from 'antd';
import { VARIABLE_TYPE } from 'src/utils/constant';
import './index.less';
import { flattenDepth } from 'lodash';

const { Search } = Input;
export default function SelectedLists(props) {
  const [keyword, setKeyword] = useState('');
  const [childKeyword, setChildKeyword] = useState('');
  const [result, setResult] = useState(props.data || []);
  const [current, setCurrent] = useState({});
  const [isShowChildren, setIsShowChildren] = useState(false);
  const [oldData, setOldData] = useState(false);
  useEffect(() => {
    if (JSON.stringify(props.data) !== JSON.stringify(oldData)) {
      if (
        props.type === VARIABLE_TYPE._FIELD ||
        props.type === VARIABLE_TYPE._STRATEGY ||
        props.type === VARIABLE_TYPE._MODEL ||
        props.type === VARIABLE_TYPE._NAMELIST
      ) {
        setIsShowChildren(true);
      }
      setKeyword('');
      setOldData(props.data);
      setResult(props.data);
      props.onHandleResultLength && props.onHandleResultLength(props.data.length);
      findCurrent();
    }
  }, [props.data]);

  useEffect(() => {
    const result = props.data.filter((item) => {
      return (
        (item.name && item.name.indexOf(keyword) !== -1) ||
        (item.code && item.code && item.code.toString().indexOf(keyword) !== -1)
      );
    });
    setResult(result);
    props.onHandleResultLength && props.onHandleResultLength(result.length);
  }, [keyword]);

  useEffect(() => {
    findCurrent();
  }, [props.value]);
  function findCurrent() {
    let cur = null;
    if (props.value) {
      if (props.type === VARIABLE_TYPE._NAMELIST) {
        const allData = flattenDepth(props.data.map((item) => item.children));
        const fa = allData.find((item) => item.code === props.value);
        cur = fa ? props.data.find((item) => item.code === fa.list_type) : null;
      } else {
        cur = props.data.find((item) => {
          if (item.code.toString() === props.value.toString().split('.')[0] || item.code.toString() === props.value) {
            return item;
          }
        });
      }
    }
    cur ? setCurrent(cur) : setCurrent({});
  }

  const filter = (e) => {
    setKeyword(e.target.value);
  };

  function onHandleClick(item) {
    if (item.disabled) {
      return;
    }
    props.onCallback(item);
  }

  //二级选择
  function onChildrenClick(item) {
    if (item.disabled) {
      return;
    }
    let value = null;
    if (props.type === VARIABLE_TYPE._NAMELIST) {
      value = {
        var_type: item.var_type,
        code: item.code,
        name: item.name,
      };
    } else {
      value = {
        var_type: item.var_type,
        code: `${current.code}.${item.code}`,
        name: `${current.name}.${item.name}`,
      };
    }
    props.onCallback(value);
  }

  function setCurrentData(item) {
    if (item.disabled) {
      return;
    }
    setCurrent(item);
  }
  return (
    <div className='selected-lists-wp'>
      <Search
        placeholder='input search text'
        value={keyword}
        allowClear
        onChange={filter}
        style={{
          width: props.type === VARIABLE_TYPE._THIRD_FEATURE || props.type === VARIABLE_TYPE._NAMELIST ? 170 : 200,
        }}
      />

      <Row type='flex' gutter={10}>
        <Col span={isShowChildren ? 12 : 24}>
          <div className={props.type === 'strategy' ? 'selected-lists selected-lists02' : 'selected-lists'}>
            {result &&
              result.map((item) => {
                return (
                  <div
                    className={
                      item.disabled
                        ? 'selected-lists-item disabled'
                        : current.code && item.code.toString() === current.code.toString()
                        ? 'selected-lists-item active'
                        : 'selected-lists-item'
                    }
                    key={item.code}
                    onClick={() =>
                      isShowChildren
                        ? setCurrentData(item)
                        : onHandleClick({
                            var_type: item.type === VARIABLE_TYPE._DATASOURCE ? item.type : props.type,
                            ...item,
                          })
                    }
                  >
                    <div className='value'>{item.code}</div>
                    <div className='label'>
                      <Tooltip title={item.name} placement='topLeft'>
                        {item.name}
                      </Tooltip>
                    </div>
                  </div>
                );
              })}
          </div>
        </Col>
        {isShowChildren && (
          <Col span={12}>
            {(props.type === VARIABLE_TYPE._THIRD_FEATURE || props.type === VARIABLE_TYPE._NAMELIST) &&
              current &&
              current.children && (
                <Search
                  placeholder='input search text'
                  value={childKeyword}
                  allowClear
                  onChange={(e) => setChildKeyword(e.target.value)}
                  style={{ width: 170, position: 'relative', top: '-30px' }}
                />
              )}

            <div
              className={props.type === VARIABLE_TYPE._STRATEGY ? 'selected-lists selected-lists02' : 'selected-lists'}
            >
              {current &&
                current.children &&
                current.children
                  .filter((item) => {
                    if (props.type === VARIABLE_TYPE._THIRD_FEATURE || props.type === VARIABLE_TYPE._NAMELIST) {
                      return (
                        (item.name && item.name.includes(childKeyword)) ||
                        (item.code && item.code.toString().includes(childKeyword))
                      );
                    }
                    return item;
                  })
                  .map((item) => {
                    return (
                      <div
                        className={
                          item.disabled
                            ? 'selected-lists-item disabled'
                            : props.value &&
                              ((item.code.toString() === props.value.toString().split('.')[1] &&
                                props.value.toString().split('.')[0] === current.code.toString()) ||
                                props.value === item.code)
                            ? 'selected-lists-item active'
                            : 'selected-lists-item'
                        }
                        key={item.code}
                        onClick={() =>
                          onChildrenClick({
                            var_type: item.type === VARIABLE_TYPE._DATASOURCE ? item.type : props.type,
                            ...item,
                          })
                        }
                      >
                        <div className='value'>
                          {props.type === VARIABLE_TYPE._NAMELIST ? item.data_name : item.code}
                        </div>
                        <div className='label'>
                          <Tooltip title={item.name} placement='topLeft'>
                            {item.name}
                          </Tooltip>
                        </div>
                      </div>
                    );
                  })}
            </div>
          </Col>
        )}
      </Row>
      {props.type === 'strategy' && (
        <div className='tips'>
          注意：系统中组件根据策略流程排布进行计算，引用的组件应在同一策略流程中排在当前组件之前，否则引用的评分卡得分或总权重值可能为空值
        </div>
      )}
    </div>
  );
}
